<template>
  <el-dialog :visible.sync="visible" :title="title" width="600px" :close-on-click-modal="false">
    <div v-loading="showForm" class="VForm">
      <VForm v-if="!showForm" :fieldList="fieldList" label-width="90px" ref="form" v-model="formData"></VForm>
    </div>
    <div slot="footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="$wait.is('account.role.*Role')">保 存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import _ from 'lodash';
import VForm from '@/components/VForm';
import request from '../../api/http';

export default {
  components: {
    VForm,
  },
  data() {
    return {
      visible: false,
      type: 'add',
      formData: {},
      changeSales: '', // 当前选中的订单
      showForm: false,
      fieldList: [
        {
          type: 'select',
          label: '销售订单',
          model: 'sales_id',
          props: {
            placeholder: '请选择销售订单',
            options: [],
          },
          on: {
            change: val => {
              this.sales_id_change(val);
            },
          },
          rules: [
            {
              required: true,
              message: '请选择销售订单',
            },
          ],
        },
        {
          type: 'input',
          label: '发动机型号',
          model: 'engine_num',
          visible: true,
          props: {
            placeholder: '请选择销售订单',
            disabled: true,
          },
        },
        {
          type: 'select',
          label: '产品件号',
          visible: true,
          model: 'materiel_id',
          props: {
            placeholder: '请选择销售订单',
            options: [],
          },
          rules: [
            {
              required: true,
              message: '请选择产品件号',
            },
          ],
          on: {
            change: val => {
              const options = this.fieldList[2].props.options;
              const index = _.findIndex(options, ['value', val]);
              if (index === -1) return;
              this.$set(this.formData, 'product_name', options[index].name);
            },
          },
        },
        {
          type: 'input',
          label: '产品件号',
          model: 'materiel_id_view',
          visible: false,
          props: {
            placeholder: '请选择销售订单',
            options: [],
            disabled: true,
          },
        },
        {
          type: 'input',
          label: '产品名称',
          model: 'product_name',
          props: {
            placeholder: '请选择销售订单或者产品件号',
            disabled: true,
          },
        },
        {
          type: 'select',
          label: '基础装配工艺',
          model: 'standard_id',
          props: {
            placeholder: '请输入基础装配工艺',
            options: this.getFormoption('ak_technology', 'num'),
          },
          rules: [
            {
              required: true,
              message: '请输入基础装配工艺',
            },
          ],
        },
        {
          type: 'input',
          label: '生产数量',
          model: 'output_count',
          props: {
            placeholder: '请输入生产数量',
          },
          on: {
            blur: val => {
              if (this.formData.output_count === -1) return; //-1不限制
              if (!this.changeSales) {
                this.$message.error('请选择销售订单后在输入数量！');
                this.formData.output_count = '';
                return;
              }
              if (!(this.formData.output_count * 1)) {
                this.$message.error('请输入数字！');
                this.formData.output_count = '';
                return;
              }
              if (this.changeSales.count < this.formData.output_count * 1) {
                this.$message.error(`当前订单最大生产数量为${this.changeSales.count}，请重新输入！`);
                this.formData.output_count = '';
              }
            },
          },
          rules: [
            {
              required: true,
              message: '请输入生产数量',
            },
          ],
        },
        {
          type: 'input',
          label: '定制工艺',
          model: 'custome_standard_no',
          props: {
            placeholder: '请输入定制工艺',
          },
        },
        {
          type: 'date',
          label: '要求完成日期',
          model: 'delivery_date',
          props: {
            placeholder: '请选择完成日期',
          },
          rules: [
            {
              required: true,
              message: '请选择完成日期',
            },
          ],
        },
        // {
        //   type: 'date',
        //   label: '实际完成日期',
        //   model: 'actual_date',
        //   props: {
        //     placeholder: '请选择实际完成日期',
        //   },
        //   rules: [
        //     {
        //       required: true,
        //       message: '请选择实际完成日期',
        //     },
        //   ],
        // },
        {
          type: 'input',
          label: '备注',
          model: 'desc',
          props: {
            placeholder: '请输入备注',
          },
        },
      ],
    };
  },

  computed: {
    title() {
      const { type } = this;
      return `${type === 'edit' ? '编辑' : '新增'}`;
    },
  },

  methods: {
    // 订单选择函数
    sales_id_change(val) {
      const options = this.fieldList[0].props.options;
      const index = _.findIndex(options, ['value', val]);
      this.changeSales = options[index].obj;
      if (!options[index].obj.engine_id) {
        this.fieldList[1].visible = false;
        this.fieldList[2].visible = false;
        this.fieldList[3].visible = true;
      } else {
        this.fieldList[1].visible = true;
        this.fieldList[2].visible = true;
        this.fieldList[3].visible = false;
        this.getMateriel(options[index].obj.engine_id);
      }
      this.$set(this.formData, 'product_name', options[index].obj.product_name);
      this.$set(this.formData, 'engine_num', options[index].obj.engine_num);
      this.$set(this.formData, 'materiel_id', options[index].obj.materiel_id);
      this.$set(this.formData, 'materiel_id_view', options[index].obj.product_num);
    },
    // 通过发动机id获取物料列表
    getMateriel(id) {
      this.fieldList[2].visible = false;
      request.get(`/materiel/api/list/engine/${id}`).then(res => {
        const data = res.data.data;
        this.fieldList[2].props.options = [];
        data.forEach(item => {
          this.fieldList[2].props.options.push({
            label: item.num,
            value: item.id,
            name: item.name,
          });
        });
        this.fieldList[2].visible = true;
      });
    },
    // 获取下拉
    getFormoption(url, key = 'name') {
      const opt = [];
      this.$api[url]
        .getList({
          page: 1,
          pageSize: 100000,
        })
        .then(({ data }) => {
          data.forEach(child => {
            opt.push({
              value: child.id,
              label: child[key] || child.num,
              obj: child,
            });
          });
        });
      return opt;
    },
    // 获取销售订单号
    getsalesList(model) {
      const opt = [];
      this.showForm = true;
      this.$api.ag_production
        .getSales({
          page: 1,
          pageSize: 10000,
        })
        .then(({ data }) => {
          data.forEach(child => {
            opt.push({
              value: child.id,
              label: child.num,
              obj: child,
            });
          });
          this.fieldList[0].props.options = opt;
          this.showForm = false;
          this.$nextTick(() => {
            this.reset();
            if (this.type === 'edit') {
              this.formData = {
                ...model,
              };
              if (this.formData.engine_id) {
                this.getMateriel(this.formData.engine_id);
              }
              this.changeSales = true;
            }
          });
        });
    },
    show(type = 'add', model) {
      this.getsalesList(model);
      this.visible = true;

      this.type = type;
    },

    close() {
      this.visible = false;
    },

    reset() {
      this.formData = {};
      this.$refs.form && this.$refs.form.resetFields();
    },

    async handleSubmit() {
      const { type } = this;
      const params = await this.$refs.form.submit();
      await this.$api.ag_production[`${type}`](params);
      this.$message.success('保存成功！');
      this.close();

      this.$emit('submit');
    },
  },
};
</script>

<style lang="scss" scoped>
.VForm {
  min-height: 300px;
}
</style>
